import router from '@/router'
import axios from 'axios'
/**
 * 封装axios请求
 */
// create an axios instance
const service = axios.create({
    // baseURL: 'http://localhost:8448',//本地请求路径
    timeout: 5000 // request timeout
})

// request 拦截器，
service.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        let userToken = JSON.parse(localStorage.getItem('dkx-user') || "{}")
        // let userToken = (localStorage.getItem('dkx-user') || "")
        

        console.log("=============userToken===== BEGIN===========");
        console.log(userToken);
        console.log("=============userToken=======END =========");

        config.headers['token'] = userToken //设置请求头
        
        //TODO: 请求拦截器，如设置Token
        return config
    },
    error => {
        // do something with request error
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截
service.interceptors.response.use(
    response => {
        
        let res = response.data

        //兼容服务器端返回的字符串数据
        if(res.code === '401') {
            router.push("/login")
        }
        
        //TODO: 响应拦截器，可以统一处理返回响应码
        return response
    },
    error => {
   
        return Promise.reject(error)
    }
)

export default service

